import { defineStore } from 'pinia'
import { ref, computed, reactive } from 'vue'
import { hotSearch, suggestSearch } from '@/api/search'
import type { Hot, SuggestionResult } from '@/types/song/index'
import { debounce } from 'lodash-es'

/**
 * 在 setup 写法的 store 中
 * ref 变量相当于 state
 * computed 相当于 getter
 * function 相当于 action
 */
export const useSearchStore = defineStore('search', () => {
  const keyWord = ref<string>('')
  const showSearchPop = ref<boolean>(false)
  const suggestLoading = ref<boolean>(false)

  const listState = reactive({
    hotList: [] as Hot[],
    suggestInfo: {} as SuggestionResult,
  })

  const setShowPop = (value: boolean) => {
    showSearchPop.value = value
  }

  // 点击热搜 item
  const changeHotKeyWord = (value: string) => {
    keyWord.value = value
    suggest()
  }

  // 默认热搜
  const getHotSearch = async () => {
    const { data } = await hotSearch()
    if (data.code !== 200) return ElMessage.error('获取失败')
    listState.hotList = data.result.hots
  }

  // 输入搜索
  const changeInputKey = debounce(() => {
    suggest()
  }, 500)

  // 搜索建议
  const suggest = async () => {
    if (keyWord.value.length === 0) return
    const { data } = await suggestSearch(keyWord.value)
    if (data.code !== 200) return ElMessage.error('获取失败')
    listState.suggestInfo = data.result
  }

  return {
    keyWord,
    showSearchPop,
    listState,
    getHotSearch,
    setShowPop,
    changeHotKeyWord,
    changeInputKey,
    suggestLoading,
  }
})
